let _ = require('lodash')
let router = require('./router')
window.HTTP_SERVER = 'http://api.timeloit.com/'
//window.HTTP_SERVER = 'http://118.242.0.43:9090/'

const site = {
    imagePath:'http://ow1op7ui7.bkt.clouddn.com/',
    publicImagePath:'http://ocpshpa2y.bkt.clouddn.com/',
    token:'',
    refreshToken:'',
    ind:0,
    url:'/index.html',
    id:0,
    type:true,
    /**
     * 截取url参数search
     * @key 参数键值
     * */
    QueryString: function (key) {
        var uri = decodeURIComponent(window.location.search);
        var re = new RegExp("[\&\?]" + key + "\=([^\&]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(key.length + 2)) : null);
    },
    QueryStrings: function(url ,key) {
        var uri = '?'+decodeURIComponent(url.split('?')[1]);
        var re = new RegExp("[\&\?]" + key + "\=([^\&]*)", "ig");
        return ((uri.match(re)) ? (uri.match(re)[0].substr(key.length + 2)) : null);
    },
    /**
     * 模板化方法
     * */
    tpl: function (id,html,datas) {
        let main = $("#"+id),tpls = $("#_"+id), tpl
        if(main.length>0){
            if(html){
                tpl = _.template(html)
            }else{
                tpl = _.template(tpls.html().replace(/&lt;/g,'<').replace(/&gt;/g,'>'))
            }
            function templates (data) {
                main.html(tpl(data))
            }
            if(datas){
                main.html(tpl(datas))
            }else{
                return templates
            }
        }
    },

    isIE: function () { //ie?
        if (!!window.ActiveXObject || "ActiveXObject" in window)
            return true;
        else
            return false;
    },

    isSafari: function (){
        if (navigator.userAgent.indexOf("Safari")>0)
            return true;
        else
            return false;
    },

    isFox: function () {
        var userAgent=window.navigator.userAgent.toLowerCase();
        if(userAgent.indexOf("firefox")>=1)
            return true;
        else
            return false;
    },
    renderList: function () {

    },
    render: function () {

    },
    link: function (url,id) {
        let _this = this,productId='',typeId=''
        this.url = url
        this.id = id
        this.ind = site.QueryString('ind')
        if((url.indexOf('?')>-1?url.split('?')[0]:url) == location.pathname){
            productId = this.QueryStrings(url,'productId')
            typeId = this.QueryStrings(url,'typeId')
            this.render(id,productId,typeId)
        }else{
            window.location.href = url + (id?(url.indexOf('?')>-1?'&':'?')+'id=' + id:'')
        }
    },
    banner: function (id,data,callback) {
        let tpl = site.tpl('main')
        site._ajax({
            type:'GET',
            url:HTTP_SERVER+'advertisement/api/advertisements/space/'+id,
            data:{},
            success: function(res){
                tpl(Object.assign({banner:res},data))
                var wid = $(document).width();
                $(".titleimg,.swiper-container1").height(wid/4+"px");
                //
                var swiper = new Swiper('.swiper-container', {
                    pagination: '.swiper-pagination',
                    paginationClickable: true
                });
                if(site.QueryString('productId') == '94094725367255040'){
                    var swiper2 = new Swiper('.swiper-container2', {
                        pagination: '.swiper-pagination',
                        paginationClickable: true,
                        autoplay: 3000,
                        loop:true
                    });
                }
                var swiper1 = new Swiper('.swiper-container1', {
                    pagination: '.swiper-pagination',
                    paginationClickable: true,
                    direction: 'vertical',
                    autoplay: 3000,
                    slidesPerView: 1,
                    loop:true
                });
                if(callback){
                    callback.apply()
                }
            }
        })
    },
    togo: function (url) {
        window.location.href = url
    },
    go: function () {
        let url = $(event.currentTarget).data('url'), id = $(event.currentTarget).data('id'), ind = $(event.currentTarget).data('ind'), type = $(event.currentTarget).data('type'), types = $(event.currentTarget).data('types')
        this.url = url
        this.id = id
        this.ind = ind
        if (url) {
            if (url == location.pathname) {
                this.render()
            } else {
                window.location.href = url + (id?(url.indexOf('?')>-1?'&':'?')+'id=' + id:'')
            }
        }
    },
    share: function(obj){
        let  _this = this
        $.ajax({
            type:'GET',
            url:HTTP_SERVER+'wechat/api/jsapi/signature?url='+encodeURIComponent(location.href),
            headers: {
                "Authorization": "Bearer " + _this.token,
            },
            data:'',
            success: function (data) {
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.appId, // 必填，公众号的唯一标识
                    timestamp: data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: data.nonceStr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });
                wx.ready(function(){
                    wx.onMenuShareTimeline({
                        title: obj.title, // 分享标题
                        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: obj.imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareAppMessage({
                        desc: obj.desc, // 分享描述
                        title: obj.title, // 分享标题
                        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: obj.imgUrl, // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareQQ({
                        desc: obj.desc, // 分享描述
                        title: obj.title, // 分享标题
                        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: obj.imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareWeibo({
                        desc: obj.desc, // 分享描述
                        title: obj.title, // 分享标题
                        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: obj.imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                    wx.onMenuShareQZone({
                        desc: obj.desc, // 分享描述
                        title: obj.title, // 分享标题
                        link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: obj.imgUrl, // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                        }
                    });
                });
            },
            error: function (xhr) {
            }
        })
    },
    _ajax: function (data) {
        let _this = this
        $.ajax(Object.assign({
            headers: {
                "Authorization": "Bearer " + _this.token,
            },
            error: function () {
            }
        },data))
    },
    reload: function (callback) {
        document.addEventListener('visibilitychange', callback)
        window.addEventListener('DOMContentLoaded', callback)
        window.addEventListener('resize', callback)
    },
    footer: function (data) {
        let ewm = '', htmls = '', logo = ''
        if($(document).width() >= 768){
            logo = '<div class="cell-1">' +
                '<div class="box">' +
                '<div class="text-center cell-1"><img style="height: 50px;position: relative;top:-10px;" src="'+site.publicImagePath+'logo/logo3.png"></div>' +
                '</div>' +
                '</div>'
            ewm = '<div class="cell-1">' +
                '<div class="box">' +
                '<div class="text-center cell-1"><img style="width: 80px;height: 80px; background:#fff;" src="'+site.publicImagePath+'sdly/ewm.jpg"><p>微信公众号</p></div>' +
                '</div>' +
                '</div>'
            htmls = ""
            //'<div class="cell-2">' +
            //'<div class="box ft-link" style="align-items: flex-start;justify-content: flex-start;"><div class="cell-1">' +
            //'<h4>按访问者</h4><ul><li><a href="/list.html?id=88410585447874560&ind=2">企业用户</a></li>' +
            //'<li><a href="/list.html?id=88410585447874560">合作伙伴</a></li>' +
            //'<li><a href="/item.html?productId=94094207500734464&typeId=88699704564539392&id=88419132101443584">新闻媒体</a></li>' +
            ////'<li><a href="/detail.html?productId=94094725367255040&id=88417748606074880">-投资者</a></li>' +
            //'<li><a href="/connect.html?id=88419388893511680">求职者</a></li></ul></div>' +
            //'<div class="cell-1"><h4>关于我们</h4><ul>' +
            //'<li><a href="/detail.html?productId=94094725367255040&id=88417748606074880">公司介绍</a></li>' +
            //'<li><a href="/detail.html?productId=94122808434544640&id=88418005008072704">企业文化</a></li><li>' +
            //'<li><a href="/time.html?productId=94093314290143232&typeId=92634065890476032&id=884187828627210244">公司资质</a></li><li>' +
            //'<li><a href="/time.html?id=88418196952006656&productId=93738813569945600&typeId=92633249746026496">公司大事件</a></li>' +
            ////'<li><a href="">-合作伙伴</a></li>' +
            //'</ul></div>' +
            //'<div class="cell-1"><h4>相关网站</h4><ul><li><a href="http://www.beijing.gov.cn/">首都之窗</a></li>' +
            //'<li><a href="http://www.bjeit.gov.cn/">北京市经信委</a></li><li><a href="http://www.bjmac.gov.cn/">北京市政市容委</a></li>' +
            //'<li><a href="http://www.bjkw.gov.cn/">北京市科委</a></li><li><a href="http://www.bjpc.gov.cn/">北京市发改委</a></li></ul></div>' +
            //'</div>' +
            //'</div>'
        }else{
        }
        let tpl = '<div class="clearfix" style="background:#445d8d;line-height: 24px;text-align: left;color: #fff">' +
            '<div class="clearfix" style="max-width: 1000px;padding: 20px 10px 10px; margin: 0 auto;"><div class="box">' +
            '<div class="cell-3"><div class="box"  style="align-items: flex-start;justify-content: flex-start;">' + htmls +
            '<p class="cell-1" style="width: 160px">总部地址：北京市朝阳区容创路17号时代凌宇大厦<br>邮政编码：100012<br>联系方式：(010)82933988<br>传&nbsp;&nbsp;&nbsp;&emsp;真：(010)82937988<br>E&nbsp;-&nbsp;mail：loithr@timeloit.com</p> ' +
            '</div></div>'+ logo + ewm +
            '</div></div></div>' +
            '<p style="line-height: 16px;padding: 10px;"><%= data.copyright%></p>'
        //+ ' <p style="line-height: 16px;padding-bottom: 10px"><%= data.copyright%></p>'
        this.tpl('footer',tpl,{data:data})
    },
    header: function () {
        let ewm = '<div class="rightmenu"></div>'
        let tpl = '<div class="leftmenu"> <img src="'+site.publicImagePath+'sdly/menu.png" /> </div>' +
            '<p class="logo"> <a href="/index.html"> <img src="'+site.publicImagePath+'sdly/logo5.png" /> </a></p>' +
            '<div class="leftnav"> <div class="dis_btn"><img src="'+site.publicImagePath+'img/error.png" /></div> <div class="fisrt_nav" id="nav"></div><div class="bac2"></div> </div>'
        this.tpl('header',tpl,{})
    },
    nav:[],
    setNav: function (callback){
        let _this = this
        _this._ajax({
            type:'GET',
            url: HTTP_SERVER+'menu/api/menus/location/SDLY_PRIMARY/items',
            data:{},
            success: function(res) {
                let arr = []
                res.map(function (val) {
                  if(val.id != '80000000000015000'){
                    arr.push(val)
                  }
                })
                _this.nav = arr

                if($(document).width() < 768) {
                    _this.type = false
                    site.tpl('nav', router.tpl, {data: arr})
                    site.bind()
                }else{
                    _this.type = true
                    site.tpl('header', router.tpls, {data: arr})
                    site.binds()
                }
                callback.apply()
            }
        })
    },
    getToken: function (callback) {
        let _this = this, type = 'password'
        if( _this.refreshToken&&window.localStorage.getItem('refresh_time')&&(window.localStorage.getItem('refresh_time') < new Date().getTime())) {
            type = _this.refreshToken
        }else{
            type = 'password'
        }
        $.ajax({
            type:'POST',
            url:HTTP_SERVER+'uaa/oauth/token',
            data:'grant_type=client_credentials',
            contentType:'application/x-www-form-urlencoded',
            headers: {
                "Authorization": "Basic aW50ZXJuYWw6aW50ZXJuYWw=",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            success: function (data) {
                _this.token = data.access_token
                _this.refreshToken = data.refresh_token
                let time = new Date().getTime() + parseInt(data.expires_in)
                window.localStorage.setItem('refresh_time',time)
                callback.apply()
            },
            error: function (xhr) {
            }
        })
    },
    binds: function () {
        $('.navs').off().on({
            mouseover:function (e) {
                $(e.currentTarget).addClass('actived').siblings().removeClass('actived')
                if( $(e.currentTarget).find('li').length>0){
                    $(e.currentTarget).find('ul').show()
                }
                $(e.currentTarget).siblings().find('ul').hide()
            }
        })
        $(".header").off().on('mouseleave',function(){
            $('.navs ul').hide()
            $('.navs').removeClass('actived')
        })
    },
    getInd: function (id) {
        for(let i = 0; i < site.nav.length; i++){
            if(id == site.nav[i].id){
                return i
            }else{
                for(let j = 0; j < site.nav[i].children.length; j++){
                    if(id == site.nav[i].children[j].id){
                        return i
                    }else{
                        for(let k = 0; k < site.nav[i].children[j].children.length; k++){
                            if(id == site.nav[i].children[j].children[k].id){
                                return i
                            }
                        }
                    }
                }
            }
        }
    },
    menuShow: function () {
        $("body").append("<div class='bac'></div>")
        $(".header .leftmenu img").hide()
        $(".leftnav").show(100);
        document.documentElement.style.overflow = 'hidden';
    },
    menuHide: function () {
        $(".bac").remove()
        $(".leftnav").hide(100);
        $(".header").find(".leftmenu img").show();
        document.documentElement.style.overflow = 'auto';
    },
    bind: function () {
        $(".header").find(".leftmenu img").click(function() {
            site.menuShow()
            $(".dis_btn img,.bac").click(function() {
                site.menuHide()
            })
        })
        $(".newcs").click(function() {
            $(".newcs").removeClass("hov")
            $(this).addClass("hov");
        })
        $(".topt").click(function() {
            if($(this).hasClass("ckcss")) {

                $(this).siblings("ul").toggle(function() {
                    $(this).hide(500, function() {
                        $(this).parent("div").removeClass("second_nav")
                        $(this).siblings(".ckcss").removeClass("ckcss");
                    })
                });
            } else {
                $(".fisrt_nav").find("div").removeClass("second_nav")
                $(".ckcss").siblings("ul").hide();
                $(".ckcss").removeClass("ckcss")
                $(this).addClass("ckcss").parent("div").addClass("second_nav")
                $(this).siblings("ul").toggle(function() {
                    $(this).animate({
                        height: 'auto',
                    }, "slow");
                });
            }
        });
    }
}

window.site = site